package com.zhuoya.healthcard.update;

import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;


import androidx.work.ExistingPeriodicWorkPolicy;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.core.cause.EndCause;
import com.liulishuo.okdownload.core.cause.ResumeFailedCause;
import com.liulishuo.okdownload.core.listener.DownloadListener1;
import com.liulishuo.okdownload.core.listener.assist.Listener1Assist;


import java.io.File;
import java.util.concurrent.TimeUnit;

public class AppUpdate {

    private static volatile AppUpdate instance;

    private AppUpdate() {}

    public static AppUpdate getInstance() {
        if (instance == null) {
            synchronized (AppUpdate.class) {
                if (instance == null) {
                    instance = new AppUpdate();
                }
            }
        }
        return instance;
    }


    public void checkUpdate(){
        PeriodicWorkRequest.Builder builder = new PeriodicWorkRequest.Builder(UpdateWorker.class, 15 , TimeUnit.MINUTES);
        WorkManager.getInstance().enqueueUniquePeriodicWork("UpdateWorker", ExistingPeriodicWorkPolicy.KEEP,builder.build());
    }


    public void startUpdate(UpdateEntity data){
        if (data==null){
            LogUtils.e("数据不能为空");
            return;
        }

        if (data.getApkUrl()==null|| TextUtils.isEmpty(data.getApkUrl())){
            LogUtils.e("下载地址不能为空");
            return;
        }

        if (data.getVersionCode()<= AppUtils.getAppVersionCode()){
            LogUtils.e("已经是最新版");
            return;
        }

        ToastUtils.showShort("开始下载");

        DownloadTask downloadTask = new DownloadTask.Builder(data.getApkUrl(), new File(getApkPath()))
                .setFilename(getApkName(data.getVersionName()))
                // the minimal interval millisecond for callback progress
                .setMinIntervalMillisCallbackProcess(30)
                // do re-download even if the task has already been completed in the past.
                .setPassIfAlreadyCompleted(false)
                .build();
        downloadTask.enqueue(new DownloadListener1() {
            @Override
            public void taskStart(@NonNull DownloadTask task, @NonNull Listener1Assist.Listener1Model model) {
                LogUtils.d("开始下载");

            }

            @Override
            public void retry(@NonNull DownloadTask task, @NonNull ResumeFailedCause cause) {

            }

            @Override
            public void connected(@NonNull DownloadTask task, int blockCount, long currentOffset, long totalLength) {

            }

            @Override
            public void progress(@NonNull DownloadTask task, long currentOffset, long totalLength) {
                LogUtils.d("已下载："+currentOffset+"/"+totalLength);

            }

            @Override
            public void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause, @NonNull Listener1Assist.Listener1Model model) {
                LogUtils.d("下载结束："+cause.name());
                if (EndCause.COMPLETED.name().equals(cause.name())){
                    File file = task.getFile();
                    if(file!=null){
                        ToastUtils.showShort("下载完成，开始安装");
                        LogUtils.d("下载完成："+file.getAbsolutePath());
                        UpdateUtil.systemInstall(file.getAbsolutePath());
                    }
                }
            }
        });

    }

    private String getApkPath(){
        return Environment.getExternalStorageDirectory().getAbsolutePath()
                +"/"+ AppUtils.getAppPackageName();
    }

    private String getApkName(String appVersion){
        return appVersion+".apk";
    }
}
